/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-use-before-define */
import { DeleteOutlined, ExclamationCircleFilled, ExportOutlined, ImportOutlined, PlusOutlined } from "@ant-design/icons";
import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components";
import type { FormInstance } from "antd";
import { Button, Divider, Drawer, Input, Modal, Space, Tag, Typography, message } from "antd";
import React, { useEffect, useRef, useState } from "react";
import DictDataForm, { DictFormData } from "./dictDataForm";
import { getPageList, remove, save, update } from "@/services/api/module/tenant/developer/dict";
import CustomerTable from "@/components/CustomerTable";
import { createTableColumns, pagination, title } from "./constants";
const { confirm } = Modal;
export type DictTypeArgs = {
	id: string;
};

export type DictDataProps = {
	onCancel?: () => void;
	open: boolean;
	dictType: string;
	statusOptions: any;
};

const DictDrawer: React.FC<DictDataProps> = props => {
	const formTableRef = useRef<FormInstance>();
	const actionRef = useRef<ActionType>();
	const [selectedRows, setSelectedRows] = useState<API.Tenant.DictData[]>([]);
	const [currentId, setCurrentId] = useState<number | undefined>(undefined);
	const [show, setShow] = useState<boolean>(false);
	const { open, onCancel = () => {}, dictType, statusOptions } = props;
	const handleColumnRemove = (record: any) => {
		showRemoveConfirm(record.id, record.dictLabel);
	};
	const handleColumnEditor = (record: any) => {
		setCurrentId(record.id);
		setShow(true);
	};
	const columns = createTableColumns(handleColumnEditor, handleColumnRemove);

	useEffect(() => {
		actionRef.current?.reload();
	}, [dictType]);

	const handleClose = () => {
		onCancel();
	};
	const handleAdd = () => {
		setShow(true);
	};

	// 关闭表单刷新列表
	const handleTableForm = async () => {
		setShow(false);
		setCurrentId(undefined);
		actionRef?.current?.reload();
	};

	// 删除警告提示
	const showRemoveConfirm = (ids: Array<number> | number, dictLabel: Array<string> | string) => {
		confirm({
			title: "警告",
			icon: <ExclamationCircleFilled />,
			content: (
				<>
					确认字典标签为：<Typography.Text strong>{dictLabel}</Typography.Text> 的数据吗，可能会导致系统异常，请慎重操作！
				</>
			),
			onOk() {
				return handleRemove(ids);
			},
			onCancel() {}
		});
	};

	// 保存
	const handleSave = async (values: DictFormData) => {
		return new Promise((resolve, reject) => {
			save({ ...values } as DictFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	// 删除
	const handleRemove = async (ids: Array<number> | number) => {
		return new Promise((reslove, reject) => {
			remove(ids)
				.then((res: any) => {
					message.success(res.msg);
					if (actionRef.current) {
						actionRef.current.reload();
					}
					reslove(true);
				})
				.catch(() => {
					reject(true);
				});
		});
	};
	// 修改
	const handleUpdate = async (values: DictFormData) => {
		return new Promise((resolve, reject) => {
			update({ ...values } as DictFormData)
				.then((res: any) => {
					message.success(res.msg);
					handleTableForm();
					resolve(true);
				})
				.catch(() => {
					reject(false);
				});
		});
	};
	const [searchValue, setSearchValue] = useState<any>(undefined);
	const handleOnSearch = async (value: any) => {
		setSearchValue({
			dictLabel: value
		});
		actionRef.current?.reload();
	};
	//数据请求
	const tableDataRequest = async (params: {} | undefined) => {
		if (dictType) {
			return await getPageList({ ...searchValue, ...{ dictType: dictType } }).then((data: any) => {
				return data;
			});
		}
	};
	return (
		<>
			<Drawer title={title} placement="right" open={open} onClose={() => handleClose()} width={1000}>
				<CustomerTable<API.Tenant.DictData>
					actionRef={actionRef}
					formRef={formTableRef}
					rowKey="id"
					key="dictDataList"
					search={false}
					ghost
					toolbar={{
						search: (
							<Space>
								<Input.Search placeholder="字典标签" allowClear style={{ width: 280 }} onSearch={handleOnSearch} />
							</Space>
						)
					}}
					tableStyle={{ minHeight: "calc(100vh - 200px)" }}
					// @ts-ignore
					request={tableDataRequest}
					columns={columns}
					rowSelection={{
						onChange: (_, selectedRows) => {
							setSelectedRows(selectedRows);
						}
					}}
					pagination={pagination}
					tableAlertRender={false}
					// @ts-ignore
					toolBarRender={() => {
						return (
							<>
								<Button type="primary" key="add" onClick={handleAdd}>
									<PlusOutlined />
									添加字典
								</Button>
								{selectedRows?.length > 0 && (
									<Button
										type="primary"
										danger
										key="remove"
										onClick={async () => {
											if (selectedRows.length <= 0) {
												message.warning("请选择一条或多条数据");
												return;
											}
											showRemoveConfirm(
												Array.from(selectedRows, ({ id }) => id),
												Array.from(selectedRows, ({ dictLabel }) => dictLabel)
											);
										}}
									>
										<DeleteOutlined />
										删除
									</Button>
								)}
							</>
						);
					}}
				/>
			</Drawer>
			<DictDataForm
				id={currentId}
				dictType={dictType}
				open={show}
				// @ts-ignore
				onSubmit={async (values: DictFormData) => {
					return values.id ? await handleUpdate(values) : handleSave(values);
				}}
				onCancel={() => {
					setShow(false);
					setCurrentId(undefined);
				}}
			/>
		</>
	);
};

export default DictDrawer;
